//
//  YNewsViewController.m
//  shijianpinggu
//
//  Created by apple on 2017/1/3.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YNewsViewController.h"
#import "YNewsTableViewCell.h"
#import "YEventInforMTTableViewController.h"
#import "YNewsModel.h"
#import "YNewsInfoViewController.h"
#import "AppDelegate.h"

@interface YNewsViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentView;
- (IBAction)segmentAction:(UISegmentedControl *)sender;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *unreadLabel;
@property (weak, nonatomic) IBOutlet UILabel *unreadLT;

@property(nonatomic,strong)NSMutableArray *massageAr;
@property(nonatomic,strong)NSMutableArray *newsAr;
@property(nonatomic,strong)NSMutableArray *ggAr;
@property(nonatomic,assign)NSInteger newsUnreadNu;
@property(nonatomic,assign)NSInteger ggUnreadNu;
@end

@implementation YNewsViewController
-(NSMutableArray *)massageAr{
    if (!_massageAr) {
        self.massageAr = [NSMutableArray new];
        
    }
    return _massageAr;
}
-(NSMutableArray *)ggAr{
    if (!_ggAr) {
        self.ggAr = [NSMutableArray new];
        
    }
    return _ggAr;
}

-(NSMutableArray *)newsAr{
    if (!_newsAr) {
        self.newsAr = [NSMutableArray new];
        
    }
    return _newsAr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.title = @"消息";
    
    [self changeUi];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"YNewsTableViewCell" bundle:nil] forCellReuseIdentifier:@"YNewsCell"];
    [self.tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"header"];
    self.newsUnreadNu = 0;
    self.ggUnreadNu = 0;
    [self hiddeUnreadLabel];
    
    //self.tabBarItem.badgeValue= @"1";
    
    [self.tabBarController.tabBar showBadgeOnItemIndex:1];
    
     [self loadDataFormUrl];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [self loadDataFormUrl];
}

-(void)hiddeUnreadLabel{
    if (self.newsUnreadNu == 0) {
        self.unreadLabel.hidden = YES;
    }else{
        self.unreadLabel.hidden = NO;
    }
    if (self.ggUnreadNu == 0) {
        self.unreadLT.hidden = YES;
    }else{
        self.unreadLT.hidden = NO;
    }
}
-(void)changeUi{
    
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone; 
    
    _segmentView.layer.borderWidth = 3;
    
    _segmentView.layer.borderColor = [UIColor whiteColor].CGColor;
    
    _segmentView.tintColor = [UIColor clearColor];//去掉颜色,现在整个segment都看不见

    CGFloat W = self.segmentView.frame.size.width;
    CGFloat H = self.segmentView.frame.size.height + 2;
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake((W-2)/2, 0, 1, H+3)];
    view1.backgroundColor = [UIColor colorWithRed:225/255.0 green:227/255.0 blue:229/255.0 alpha:1];
   
    [self.segmentView addSubview:view1];
    
    
    
    //修改字体的默认颜色与选中颜色
    [self.segmentView setTitleTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor colorWithRed:35/255.0 green:37/255.0 blue:40/255.0 alpha:1]} forState:UIControlStateNormal];
    [self.segmentView setTitleTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor colorWithRed:0 green:69/255.0 blue:189/255.0 alpha:1]} forState:UIControlStateSelected];
    //控件切圆角
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.unreadLabel.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:self.unreadLabel.bounds.size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
    //设置大小
    maskLayer.frame = self.unreadLabel.bounds;
    //设置图形样子
    maskLayer.path = maskPath.CGPath;
    self.unreadLabel.layer.mask = maskLayer;
    
    //控件切圆角
    UIBezierPath *maskPath1 = [UIBezierPath bezierPathWithRoundedRect:self.unreadLT.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:self.unreadLT.bounds.size];
    CAShapeLayer *maskLayer1 = [[CAShapeLayer alloc]init];
    //设置大小
    maskLayer1.frame = self.unreadLT.bounds;
    //设置图形样子
    maskLayer1.path = maskPath1.CGPath;
    self.unreadLT.layer.mask = maskLayer1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.massageAr.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YNewsCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    YNewsModel *model = self.massageAr[indexPath.row];
    [cell.imageV sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:[UIImage imageNamed:@"yuan_ll"]];

    cell.timeLable.text = model.addtime;
    cell.titleLable.text = model.title;
    if ([model.is_read integerValue]== 1) {
        cell.unreadLable.hidden = YES;
    }else{
        cell.unreadLable.hidden = NO;
    }
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return 10;
//}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //self.hidesBottomBarWhenPushed = YES;
    YNewsModel *model = self.massageAr[indexPath.row];
    
    
    YNewsInfoViewController *eventIF = [YNewsInfoViewController new];
    
    eventIF.newsid = model.newsid;
    YNewsTableViewCell *cell = [tableView  cellForRowAtIndexPath:indexPath];
    
    cell.unreadLable.hidden = YES;
    
    if (self.segmentView.selectedSegmentIndex == 0) {
        if ([model.is_read integerValue] == 0) {
            self.newsUnreadNu = self.newsUnreadNu-1;
            self.unreadLabel.text = [NSString stringWithFormat:@"%ld",(long)self.newsUnreadNu];
            model.is_read = @"1";
        }
        
    }else{
        if ([model.is_read integerValue] == 0) {
            self.ggUnreadNu = self.ggUnreadNu-1;
            self.unreadLT.text = [NSString stringWithFormat:@"%ld",(long)self.ggUnreadNu];
            model.is_read = @"1";
        }
        
    }
    //        冒泡排序  根据已读未读
    
    //        冒泡排序  根据日期
    for(int i = 0;i < [self.massageAr count]-1;i++){
        for(int j = i+1;j<[self.massageAr count];j++){
            YNewsModel *modeli = self.massageAr[i];
            YNewsModel *modelj = self.massageAr[j];
            NSString *datai = modeli.addtime;
            NSString *dataj = modelj.addtime;
            
            if([self compareDate:datai withDate:dataj] == 1) {
                //交换
                [self.massageAr exchangeObjectAtIndex:i withObjectAtIndex:j];
            }
        
        for(int i = 0;i < [self.massageAr count]-1;i++){
            for(int j = i+1;j<[self.massageAr count];j++){
                YNewsModel *modeli = self.massageAr[i];
                YNewsModel *modelj = self.massageAr[j];
                int numi=  [modeli.is_read intValue];
                int numj= [modelj.is_read intValue];
                
                if(numi>numj) {
                    //交换
                    [self.massageAr exchangeObjectAtIndex:i withObjectAtIndex:j];
                }
            }
        }
        }

    }
    [self hiddeUnreadLabel];
    
    if (self.newsUnreadNu + self.ggUnreadNu > 0) {
        [self.tabBarController.tabBar showBadgeOnItemIndex:1];
    }else{
        [self.tabBarController.tabBar hideBadgeOnItemIndex:1];
    }
    
    [self.tableView reloadData];
    
    [self showViewController: eventIF sender:nil];

    
    //self.hidesBottomBarWhenPushed = NO;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)segmentAction:(UISegmentedControl *)sender {
    
    
    
    if (sender.selectedSegmentIndex == 0) {
        self.massageAr = self.newsAr;
    }else if(sender.selectedSegmentIndex == 1){
        self.massageAr = self.ggAr;

    }
    
    if (self.massageAr.count == 0) {
        return;
    }else{
        //        冒泡排序  根据日期
    for(int i = 0;i < [self.massageAr count]-1;i++){
        for(int j = i+1;j<[self.massageAr count];j++){
            YNewsModel *modeli = self.massageAr[i];
            YNewsModel *modelj = self.massageAr[j];
            NSString *datai = modeli.addtime;
            NSString *dataj = modelj.addtime;
            
            if([self compareDate:datai withDate:dataj] == 1) {
                //交换
                [self.massageAr exchangeObjectAtIndex:i withObjectAtIndex:j];
            }
        }
        
        //        冒泡排序  根据已读未读
        for(int i = 0;i < [self.massageAr count]-1;i++){
            for(int j = i+1;j<[self.massageAr count];j++){
                YNewsModel *modeli = self.massageAr[i];
                YNewsModel *modelj = self.massageAr[j];
                int numi=  [modeli.is_read intValue];
                int numj= [modelj.is_read intValue];
                
                if(numi>numj) {
                    //交换
                    [self.massageAr exchangeObjectAtIndex:i withObjectAtIndex:j];
                }
            }
        }
        

    }

    [self.tableView reloadData];
    }
}
//请求数据
-(void)loadDataFormUrl{
    
    
    NSDictionary *parameter = @{@"contactid":[[NSUserDefaults standardUserDefaults] stringForKey:@"userid"]};
    
    //    NSLog(@"%@",dict);
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:@"http://wangan.ldynet.cn/index.php/Notice/news" parameters:parameter constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        [self.newsAr removeAllObjects];
        [self.ggAr removeAllObjects];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@", dic);
        NSArray *evAr = dic[@"list"];
        NSDictionary *newsListDic = evAr[0][@"newlist"];
        NSMutableArray *newsListAr = [NSMutableArray new];
        
        [newsListAr addObjectsFromArray:newsListDic[@"wd"]];
        [newsListAr addObjectsFromArray:newsListDic[@"yd"]];
             for (NSDictionary *dic in newsListAr) {
            YNewsModel *emodel = [[YNewsModel alloc] init];
            [emodel setValuesForKeysWithDictionary:dic];
            [self.newsAr addObject:emodel];
        }
        self.newsUnreadNu = [evAr[0][@"newlistnum"] integerValue];
        self.unreadLabel.text = [NSString stringWithFormat:@"%ld",(long)self.newsUnreadNu];
        NSLog(@"%@",self.newsAr);
        
        
        
        NSDictionary *ggListDic = evAr[0][@"noticelist"];
        NSMutableArray *ggListAr = [NSMutableArray new];
        [ggListAr addObjectsFromArray:ggListDic[@"wd"]];
        [ggListAr addObjectsFromArray:ggListDic[@"yd"]];
       
        for (NSDictionary *dic in ggListAr) {
            YNewsModel *emodel = [[YNewsModel alloc] init];
            [emodel setValuesForKeysWithDictionary:dic];
            [self.ggAr addObject:emodel];
        }
        NSLog(@"%@",self.ggAr);
        
        self.ggUnreadNu = [evAr[0][@"noticelistnum"] integerValue];
        self.unreadLT.text = [NSString stringWithFormat:@"%ld",(long)self.ggUnreadNu];
        
        
        self.massageAr = self.newsAr;
        
        
        //        冒泡排序  根据日期
        for(int i = 0;i < [self.massageAr count]-1;i++){
            for(int j = i+1;j<[self.massageAr count];j++){
                YNewsModel *modeli = self.massageAr[i];
                YNewsModel *modelj = self.massageAr[j];
                NSString *datai = modeli.addtime;
                NSString *dataj = modelj.addtime;
                
                if([self compareDate:datai withDate:dataj] == 1) {
                    //交换
                    [self.massageAr exchangeObjectAtIndex:i withObjectAtIndex:j];
                }
            }
        }
        //        冒泡排序  根据已读未读
        for(int i = 0;i < [self.massageAr count]-1;i++){
            for(int j = i+1;j<[self.massageAr count];j++){
                YNewsModel *modeli = self.massageAr[i];
                YNewsModel *modelj = self.massageAr[j];
                int numi=  [modeli.is_read intValue];
                int numj= [modelj.is_read intValue];
                
                if(numi>numj) {
                    //交换
                    [self.massageAr exchangeObjectAtIndex:i withObjectAtIndex:j];
                }
            }
        }

        
        if (self.newsUnreadNu + self.ggUnreadNu > 0) {
            [self.tabBarController.tabBar showBadgeOnItemIndex:1];
        }else{
            [self.tabBarController.tabBar hideBadgeOnItemIndex:1];
        }
        [self hiddeUnreadLabel];


        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 请求失败
        // [self alertWithString:@"请稍后再试"];
    }];
    
    
    //[self loginUrl];
}

-(NSInteger)compareDate:(NSString*)aDate withDate:(NSString*)bDate
{
    NSInteger aa = 0;
    NSDateFormatter *dateformater = [[NSDateFormatter alloc] init];
    [dateformater setDateFormat:@"yyyy-MM-dd"];
    
    
    NSDate *dta = [dateformater dateFromString:aDate];
    NSDate *dtb = [dateformater dateFromString:bDate];
    NSComparisonResult result = [dta compare:dtb];
    if (result==NSOrderedSame)
    {
        //        相等  aa=0
    }else if (result==NSOrderedAscending)
    {
        //bDate比aDate大
        aa=1;
    }else if (result==NSOrderedDescending)
    {
        //bDate比aDate小
        aa=-1;
        
    }
    return aa;
}
@end
